const express = require('express');
const { avatar, picture, logo, file } = require('../utils/upload');
const router = express.Router();

router
	// 头像
	.post('/avatar', avatar.single('avatar'), async (req, res) => {
		if (!req.file) {
			return res.send({
				success: false,
				message: '请选择一张图片'
			});
		}
		res.send({
			success: true,
			message: '上传成功',
			url: '/avatars/' + req.file?.filename
		});
	})
	// 图片
	.post('/picture', picture.single('picture'), async (req, res) => {
		if (!req.file) {
			return res.send({
				success: false,
				message: '请选择一张图片'
			});
		}
		res.send({
			success: true,
			message: '上传成功',
			url: '/pictures/' + req.file?.filename
		});
	})
	// logo
	.post('/logo', logo.single('logo'), async (req, res) => {
		if (!req.file) {
			return res.send({
				success: false,
				message: '请选择一张图片'
			});
		}
		res.send({
			success: true,
			message: '上传成功',
			url: '/logos/' + req.file?.filename
		});
	})
	// 文件
	.post('/file', file.single('file'), async (req, res) => {
		if (!req.file) {
			return res.send({
				success: false,
				message: '请选择一份文件'
			});
		}
		res.send({
			success: true,
			message: '上传成功',
			url: '/files/' + req.file?.filename
		});
	})
	// 上传多张文件
	.post('/files', file.array('files', 10), async (req, res) => {
		if (!req.files) {
			return res.send({
				success: false,
				message: '请选择一份文件'
			});
		}
		// let urls = req.files.map((f) => '/files/' + f.filename);
		res.send({
			success: true,
			message: '上传成功',
			urls: req.files
		});
	});

// 挂接
const Router = (app) => {
	app.use('/upload', router);
};

module.exports = { Router };
